package com.ovopark.organize.server.controller;


import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ovopark.organize.common.base.BaseResult;
import com.ovopark.organize.server.common.support.LocalStorageUtils;
import com.ovopark.organize.server.model.entity.*;
import com.ovopark.organize.server.model.query.FranchiseesApprovalAddressQuery;
import com.ovopark.organize.server.model.vo.FranchiseesApprovalTemplateValueVo;
import com.ovopark.organize.server.service.*;
import com.ovopark.organize.server.util.CollectionUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author wxb
 * @description: 加盟商立项
 * @param:
 * @return:
 * @date: 2024/4/11 16:54
 */
@Slf4j
@RestController
@RequestMapping("/franchiseesApproval")
public class FranchiseesApprovalController {
    @Resource
    private FranchiseesApprovalTemplateService franchiseesApprovalTemplateService;

    @Resource
    private FranchiseesApprovalTemplateFieldValueService franchiseesApprovalTemplateFieldValueService;

    @Resource
    private FranchiseesApprovalAddressService franchiseesApprovalAddressService;

    @Resource
    private FranchiseesApprovalTemplateUserService franchiseesApprovalTemplateUserService;

    @Resource
    private FranchiseesApprovalTemplateGroupService franchiseesApprovalTemplateGroupService;

    @Resource
    private UserService userService;

    /**
     * @description: 新增选址点位 页面 新增
     * @param: [vo]
     * @return: com.ovopark.organize.common.base.BaseResult
     * @author wxb
     * @date: 2024/4/12 9:21
     */
    @PostMapping("/saveOrUpdateAddress")
    public BaseResult saveOrUpdateAddress(@RequestBody FranchiseesApprovalAddress vo) {
        Integer userId = LocalStorageUtils.getStorageInfo().getUserId();
        Integer curGroupId = LocalStorageUtils.getStorageInfo().getGroupId();
        if (userId == null) {
            return BaseResult.invalidToken();
        }
        if (curGroupId != null) {
            vo.setGroupId(curGroupId);
        }
        // 新增
        if (vo.getId() == null) {
            vo.setCreateId(userId);
            vo.setCreateTime(LocalDateTime.now());
        } else {
            // 修改
            vo.setUpdateId(userId);
            vo.setUpdateTime(LocalDateTime.now());
        }
        FranchiseesApprovalAddress address = franchiseesApprovalAddressService.saveOrUpdateAddress(vo);
        return BaseResult.success(address);
    }

    /**
     * @description: 选址点位 页面 检索
     * @param: [query]
     * @return: com.ovopark.organize.common.base.BaseResult
     * @author wxb
     * @date: 2024/4/11 16:57
     */
    @PostMapping("/getAddressList")
    public BaseResult getAddressList(@RequestBody FranchiseesApprovalAddressQuery query) {
        Integer userId = LocalStorageUtils.getStorageInfo().getUserId();
        Integer curGroupId = LocalStorageUtils.getStorageInfo().getGroupId();
        if (userId == null) {
            return BaseResult.invalidToken();
        }
        Map<String, Object> result = new HashMap<>();
        result.put("total", 0);
        result.put("data", null);
        Integer pageSize = query.getPageSize();
        Integer pageNumber = query.getPageNumber();
        Integer groupId = query.getGroupId();
        if (curGroupId != null) {
            groupId = curGroupId;
        }
        Page<FranchiseesApprovalAddress> page = new Page<>(pageNumber, pageSize);
        IPage<FranchiseesApprovalAddress> list = franchiseesApprovalAddressService.page(page, groupId, query);
        if (CollectionUtil.isNotEmpty(list.getRecords())) {
            result.put("total", list.getTotal());
            result.put("data", list.getRecords());
        }
        return BaseResult.success(result);
    }

    /**
     * @description: 地址下的评估记录列表 分页
     * @param: [addressId, groupId]
     * @return: com.ovopark.organize.common.base.BaseResult
     * @author wxb
     * @date: 2024/6/4 15:52
     */
    @GetMapping("/getRecordsByAddressId")
    public BaseResult getRecordsByAddressId(@RequestParam Integer addressId, @RequestParam Integer groupId, @RequestParam(value = "pageNumber", defaultValue = "1") Integer pageNumber,
                                                        @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize) {
        Integer userId = LocalStorageUtils.getStorageInfo().getUserId();
        if (userId == null) {
            return BaseResult.invalidToken();
        }
        Integer curGroupId = LocalStorageUtils.getStorageInfo().getGroupId();
        if (curGroupId != null) {
            groupId = curGroupId;
        }
        Map<String, Object> result = new HashMap<>();
        result.put("total", 0);
        result.put("data", null);
        Page<FranchiseesApprovalTemplateUser> page = new Page<>(pageNumber, pageSize);
        IPage<FranchiseesApprovalTemplateUser> list = franchiseesApprovalTemplateUserService.page(page, groupId, addressId);
        if (CollectionUtil.isNotEmpty(list.getRecords())) {
            result.put("total", list.getTotal());
            result.put("data", list.getRecords());
        }
        return BaseResult.success(result);
    }

    /**
     * @description: 删除记录 地址下的评估记录
     * @param: [id]
     * @return: com.ovopark.organize.common.base.BaseResult
     * @author wxb
     * @date: 2024/6/27 14:08
     */
    @PostMapping("/deleteRecordById")
    public BaseResult deleteRecordById(@RequestBody Map<String, Object> parameters) {
        Integer id = (Integer) parameters.get("id");
        if (id == null) {
            return BaseResult.paramError();
        }
        Integer userId = LocalStorageUtils.getStorageInfo().getUserId();
        if (userId == null) {
            return BaseResult.invalidToken();
        }
        Integer groupId = LocalStorageUtils.getStorageInfo().getGroupId();
        // 获取
        FranchiseesApprovalTemplateUser templateUser = franchiseesApprovalTemplateUserService.getById(id);
        if (templateUser != null && templateUser.getGroupId().equals(groupId)) {
            templateUser.setIsDeleted(1);
            franchiseesApprovalTemplateUserService.saveOrUpdateById(templateUser);
        }
        return BaseResult.success();
    }

    /**
     * @description: 地址下的线索列表 分页
     * @param: [addressId, groupId]
     * @return: com.ovopark.organize.common.base.BaseResult
     * @author wxb
     * @date: 2024/6/4 15:52
     */
    @GetMapping("/getFranchiseesRegistrationByAddressId")
    public BaseResult getFranchiseesRegistrationByAddressId(@RequestParam Integer addressId, @RequestParam Integer groupId, @RequestParam(value = "pageNumber", defaultValue = "1") Integer pageNumber,
                                                        @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize) {
        Integer userId = LocalStorageUtils.getStorageInfo().getUserId();
        if (userId == null) {
            return BaseResult.invalidToken();
        }
        Integer curGroupId = LocalStorageUtils.getStorageInfo().getGroupId();
        if (curGroupId != null) {
            groupId = curGroupId;
        }
        Map<String, Object> result = new HashMap<>();
        result.put("total", 0);
        result.put("data", null);
        Page<FranchiseesRegistration> page = new Page<>(pageNumber, pageSize);
        IPage<FranchiseesRegistration> list = franchiseesApprovalAddressService.getPageByAddressId(page, groupId, addressId);
        if (CollectionUtil.isNotEmpty(list.getRecords())) {
            result.put("total", list.getTotal());
            result.put("data", list.getRecords());
        }
        return BaseResult.success(result);
    }

    /**
     * @description: 选址点位 页面 批量删除
     * @param: [idList]
     * @return: com.ovopark.organize.common.base.BaseResult
     * @author wxb
     * @date: 2024/6/11 18:24
     */
    @RequestMapping("/batchDeleteAddress")
    public BaseResult batchDeleteAddress(@RequestBody List<Integer> idList) {
        Integer userId = LocalStorageUtils.getStorageInfo().getUserId();
        if (userId == null) {
            return BaseResult.invalidToken();
        }
        if (CollectionUtil.isEmpty(idList)) {
            return BaseResult.paramError();
        }
        franchiseesApprovalAddressService.batchDeleteAddress(idList);
        return BaseResult.success();
    }

    /**
     * @description: 选址点位 页面 单个删除
     * @param: [id]
     * @return: com.ovopark.organize.common.base.BaseResult
     * @author wxb
     * @date: 2024/6/11 18:24
     */
    @RequestMapping("/deleteAddress")
    public BaseResult deleteAddress(@RequestParam Integer id) {
        Integer userId = LocalStorageUtils.getStorageInfo().getUserId();
        if (userId == null) {
            return BaseResult.invalidToken();
        }
        if (id == null) {
            return BaseResult.paramError();
        }
        franchiseesApprovalAddressService.deleteAddress(id);
        return BaseResult.success();
    }

    /**
     * @description: 创建模板 编辑模板
     * @param: [vo]
     * @return: com.ovopark.organize.common.base.BaseResult
     * @author wxb
     * @date: 2024/4/12 11:09
     */
    @PostMapping("/saveTemplate")
    public BaseResult saveTemplate(@RequestBody FranchiseesApprovalTemplate template) {
        Integer userId = LocalStorageUtils.getStorageInfo().getUserId();
        Integer curGroupId = LocalStorageUtils.getStorageInfo().getGroupId();
        if (userId == null) {
            return BaseResult.invalidToken();
        }
        if (curGroupId != null) {
            template.setGroupId(curGroupId);
        }
        // 新增
        if (template.getId() == null) {
            template.setCreateId(userId);
            template.setCreateTime(LocalDateTime.now());
        } else {
            // 修改
            template.setUpdateId(userId);
            template.setUpdateTime(LocalDateTime.now());
        }
        template = franchiseesApprovalTemplateService.saveTemplate(template);
        return BaseResult.success(template);
    }

    /** 
     * @description: 模板开关
     * @param: [parameters]
     * @return: com.ovopark.organize.common.base.BaseResult
     * @author wxb
     * @date: 2024/4/25 15:44
     */ 
    @PostMapping("/onOffTemplate")
    public BaseResult onOffTemplate(@RequestBody Map<String, Object> parameters) {
        Integer userId = LocalStorageUtils.getStorageInfo().getUserId();
        Integer curGroupId = LocalStorageUtils.getStorageInfo().getGroupId();
        Integer groupId = (Integer) parameters.get("groupId");
        Integer id = (Integer) parameters.get("id");
        Integer open = (Integer) parameters.get("open");
        if (userId == null) {
            return BaseResult.invalidToken();
        }
        if (curGroupId != null) {
            groupId = curGroupId;
        }
        Boolean success = franchiseesApprovalTemplateService.onOffTemplate(id, open, groupId, userId);
        if (!success) {
            return BaseResult.error();
        }
        return BaseResult.success();
    }

    /**
     * @description: 获取企业的模板 包含系统模板 模板列表
     * @param: [groupId]
     * @return: com.ovopark.organize.common.base.BaseResult
     * @author wxb
     * @date: 2024/4/12 15:18
     */
    @GetMapping("/getTemplateByGroupId")
    public BaseResult getTemplateByGroupId(@RequestParam(value = "pageNumber", defaultValue = "1") Integer pageNumber,
                                           @RequestParam(value = "pageSize", defaultValue = "20") Integer pageSize,
                                           @RequestParam Integer groupId, @RequestParam(required = false) Integer open) {
        Integer userId = LocalStorageUtils.getStorageInfo().getUserId();
        Integer curGroupId = LocalStorageUtils.getStorageInfo().getGroupId();
        if (userId == null) {
            return BaseResult.invalidToken();
        }
        if (curGroupId != null) {
            groupId = curGroupId;
        }
        Map<String, Object> result = new HashMap<>();
        IPage<FranchiseesApprovalTemplate> templateList = franchiseesApprovalTemplateService.getTemplateByGroupId(pageSize, pageNumber, groupId, open);
        List<FranchiseesApprovalTemplate> records = templateList.getRecords();
        if (CollectionUtil.isNotEmpty(records)) {
            for (FranchiseesApprovalTemplate template : records) {
                // 版本号
                List<String> versions = franchiseesApprovalTemplateService.getVersionListByTemplateId(template.getId(), null, groupId);
                if (CollectionUtil.isNotEmpty(versions)) {
                    template.setVersion(versions.get(0));
                }
                if (template.getGroupId() == null) {
                    FranchiseesApprovalTemplateGroup templateGroup = franchiseesApprovalTemplateGroupService.getGroupTemplate(groupId, template.getId());
                    if (templateGroup != null) {
                        template.setTemplateName(templateGroup.getTemplateName());
                        template.setTemplateDesc(templateGroup.getTemplateDesc());
                        template.setIsOpen(templateGroup.getIsOpen());
                        template.setUpdateId(templateGroup.getUpdateId());
                        if (templateGroup.getUpdateId() != null) {
                            Users users = userService.getUsersById(templateGroup.getUpdateId());
                            template.setUpdateUser(users.getShowName());
                        }
                        template.setUpdateTime(templateGroup.getUpdateTime());
                    } else {
                        FranchiseesApprovalTemplate defaultTemplate = franchiseesApprovalTemplateService.getDefaultTemplate(groupId);
                        // 已经开启了自己企业下的模板
                        if (defaultTemplate != null) {
                            template.setIsOpen(0);
                        }
                    }
                    template.setCreateUser("系统默认");
                }
            }
            result.put("total", templateList.getTotal());
            result.put("data", records);
        }
        return BaseResult.success(result);
    }

    /** 
     * @description: 获取模板 根据模板ID
     * @param: [groupId]
     * @return: com.ovopark.organize.common.base.BaseResult
     * @author wxb
     * @date: 2024/6/1 13:02
     */ 
    @GetMapping("/getTemplate")
    public BaseResult getTemplate(@RequestParam Integer templateId) {
        Integer userId = LocalStorageUtils.getStorageInfo().getUserId();
        if (userId == null) {
            return BaseResult.invalidToken();
        }
        Integer groupId = LocalStorageUtils.getStorageInfo().getGroupId();
        // 获取企业开启的模板
        FranchiseesApprovalTemplate template = franchiseesApprovalTemplateService.getTemplateById(templateId, groupId);
        return BaseResult.success(template);
    }

    /**
     * @description: 获取企业开启的模板
     * @param: [groupId]
     * @return: com.ovopark.organize.common.base.BaseResult
     * @author wxb
     * @date: 2024/4/16 16:26
     */
    @GetMapping("/getDefaultTemplateByGroupId")
    public BaseResult getDefaultTemplateByGroupId(@RequestParam Integer groupId) {
        Integer userId = LocalStorageUtils.getStorageInfo().getUserId();
        Integer curGroupId = LocalStorageUtils.getStorageInfo().getGroupId();
        if (userId == null) {
            return BaseResult.invalidToken();
        }
        if (curGroupId != null) {
            groupId = curGroupId;
        }
        // 获取开启的模板
        FranchiseesApprovalTemplate template = franchiseesApprovalTemplateService.getDefaultTemplate(groupId);
        return BaseResult.success(template);
    }

    /** 
     * @description: 删除模板
     * @param: [id]
     * @return: com.ovopark.organize.common.base.BaseResult
     * @author wxb
     * @date: 2024/4/25 15:15
     */ 
    @RequestMapping("/deleteTemplate")
    public BaseResult deleteTemplate(@RequestParam Integer id) {
        Integer userId = LocalStorageUtils.getStorageInfo().getUserId();
        if (userId == null) {
            return BaseResult.invalidToken();
        }
        if (id == null) {
            return BaseResult.paramError();
        }
        franchiseesApprovalTemplateService.deleteById(id);
        return BaseResult.success();
    }

    /**
     * @description: 获取模板字段
     * @param: [templateId, groupId]
     * @return: com.ovopark.organize.common.base.BaseResult
     * @author wxb
     * @date: 2024/4/12 15:16
     */
    @GetMapping("/getTemplateFieldsConf")
    public BaseResult getTemplateFieldsConf(@RequestParam Integer templateId, @RequestParam Integer groupId, @RequestParam(value = "version", required = false) String version){
        Integer userId = LocalStorageUtils.getStorageInfo().getUserId();
        Integer curGroupId = LocalStorageUtils.getStorageInfo().getGroupId();
        if (userId == null) {
            return BaseResult.invalidToken();
        }
        if (templateId == null) {
            return BaseResult.paramError();
        }
        if (curGroupId != null) {
            groupId = curGroupId;
        }
        FranchiseesApprovalTemplate template = franchiseesApprovalTemplateService.getTemplateFields(templateId, groupId, version);
        return BaseResult.success(template);
    }

    /**
     * @description: 配置模板字段
     * @param: [vo]
     * @return: com.ovopark.organize.common.base.BaseResult
     * @author wxb
     * @date: 2024/4/16 16:45
     */
    @PostMapping("/saveTemplateFieldsConf")
    public BaseResult saveTemplateFieldsConf(@RequestBody FranchiseesApprovalTemplate template) {
        Integer userId = LocalStorageUtils.getStorageInfo().getUserId();
        if (userId == null) {
            return BaseResult.invalidToken();
        }
        if (template == null) {
            return BaseResult.paramError();
        }
        List<FranchiseesApprovalTemplateSection> list = franchiseesApprovalTemplateService.saveTemplateFieldsConf(template, userId);
        template.setSectionList(list);
        return BaseResult.success(template);
    }

    /** 
     * @description: 线索下的点位
     * @param: [registrationId, groupId]
     * @return: com.ovopark.organize.common.base.BaseResult
     * @author wxb
     * @date: 2024/6/6 17:23
     */ 
    @GetMapping("/getAddressListByRegistrationId")
    public BaseResult getAddressListByRegistrationId(@RequestParam Integer registrationId, @RequestParam Integer groupId) {
        Integer userId = LocalStorageUtils.getStorageInfo().getUserId();
        Integer curGroupId = LocalStorageUtils.getStorageInfo().getGroupId();
        if (userId == null) {
            return BaseResult.invalidToken();
        }
        if (registrationId == null) {
            return BaseResult.paramError();
        }
        if (curGroupId != null) {
            groupId = curGroupId;
        }
        List<FranchiseesApprovalAddress> list = franchiseesApprovalAddressService.getByRegistrationId(registrationId, groupId);
        return BaseResult.success(list);
    }

    /**
     * @description: 获取模板字段值
     * @param: [templateId, groupId]
     * @return: com.ovopark.organize.common.base.BaseResult
     * @author wxb
     * @date: 2024/4/14 12:19
     */
    @GetMapping("/getTemplateFieldValue")
    public BaseResult getTemplateFieldValue(@RequestParam Integer templateUserId, @RequestParam Integer groupId) {
        Integer userId = LocalStorageUtils.getStorageInfo().getUserId();
        Integer curGroupId = LocalStorageUtils.getStorageInfo().getGroupId();
        if (userId == null) {
            return BaseResult.invalidToken();
        }
        if (templateUserId == null) {
            return BaseResult.paramError();
        }
        if (curGroupId != null) {
            groupId = curGroupId;
        }
        FranchiseesApprovalTemplate template = franchiseesApprovalTemplateService.getTemplateFieldValue(templateUserId, groupId);
        return BaseResult.success(template);
    }

    /**
     * @description: 保存模板字段值
     * @param: [vo]
     * @return: com.ovopark.organize.common.base.BaseResult
     * @author wxb
     * @date: 2024/4/16 19:10
     */
    @PostMapping("/saveTemplateFieldValue")
    public BaseResult saveTemplateFieldValue(@RequestBody FranchiseesApprovalTemplateValueVo userValueVo) {
        Integer userId = LocalStorageUtils.getStorageInfo().getUserId();
        Integer curGroupId = LocalStorageUtils.getStorageInfo().getGroupId();
        if (userId == null) {
            return BaseResult.invalidToken();
        }
        if (curGroupId != null) {
            userValueVo.setGroupId(curGroupId);
        }
        if (userValueVo == null || CollectionUtil.isEmpty(userValueVo.getValueList())) {
            return BaseResult.paramError();
        }
        franchiseesApprovalTemplateFieldValueService.saveValue(userValueVo, userId);
        return BaseResult.success();
    }

    /** 
     * @description: 地址绑定线索
     * @param: [parameters]
     * @return: com.ovopark.organize.common.base.BaseResult
     * @author wxb
     * @date: 2024/6/11 20:57
     */ 
    @PostMapping("/addRegistration")
    public BaseResult addRegistration(@RequestBody Map<String, Object> parameters) {
        Integer userId = LocalStorageUtils.getStorageInfo().getUserId();
        Integer curGroupId = LocalStorageUtils.getStorageInfo().getGroupId();
        if (userId == null) {
            return BaseResult.invalidToken();
        }
        Integer groupId = (Integer) parameters.get("groupId");
        Integer addressId = (Integer) parameters.get("addressId");
        Integer registrationId = (Integer) parameters.get("registrationId");
        if (curGroupId != null) {
            groupId = curGroupId;
        }
        if (addressId == null || registrationId == null) {
            return BaseResult.paramError();
        }
        franchiseesApprovalAddressService.addRegistration(groupId, addressId, registrationId, userId);
        return BaseResult.success();
    }

    /** 
     * @description: 移除线索
     * @param: [parameters]
     * @return: com.ovopark.organize.common.base.BaseResult
     * @author wxb
     * @date: 2024/6/12 10:12
     */ 
    @PostMapping("/removeRegistration")
    public BaseResult removeRegistration(@RequestBody Map<String, Object> parameters) {
        Integer userId = LocalStorageUtils.getStorageInfo().getUserId();
        Integer curGroupId = LocalStorageUtils.getStorageInfo().getGroupId();
        if (userId == null) {
            return BaseResult.invalidToken();
        }
        Integer groupId = (Integer) parameters.get("groupId");
        Integer addressId = (Integer) parameters.get("addressId");
        Integer registrationId = (Integer) parameters.get("registrationId");
        if (curGroupId != null) {
            groupId = curGroupId;
        }
        if (addressId == null || registrationId == null) {
            return BaseResult.paramError();
        }
        franchiseesApprovalAddressService.removeRegistration(groupId, addressId, registrationId, userId);
        return BaseResult.success();
    }
}
